//
//  QuestionVC.m
//  PCAForWar
//
//  Created by dllo on 16/3/9.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "QuestionVC.h"
#import "QuestionTabViewCell.h"
#import "HandleData.h"
#import <UIImageView+WebCache.h>
#import "ModelQuestion.h"
#import <MJRefresh.h>
#import <DKNightVersion.h>


#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface QuestionVC () <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property (nonatomic, retain) UIView *viewForTitle;
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UIImageView *imageForHead;
@property (nonatomic, retain) NSString *picurl;
@property (nonatomic, retain) UIView *viewForText;
@property (nonatomic, retain) UILabel *lableText;
@property (nonatomic ,retain) UILabel *labelForFollow;
@property (nonatomic, retain) UIButton *buttonForBack;
@property (nonatomic, retain) NSMutableArray *arrModel;
@property (nonatomic, retain) UIView *viewForField;
@property (nonatomic, retain) UITextField *textField;
@property (nonatomic, retain) UILabel *labelForTitle;
@property (nonatomic, retain) UIButton *buttonSend;
@property (nonatomic, retain) NSString *strText;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, assign) NSInteger number;

@end

@implementation QuestionVC

- (void)dealloc{
    
    [_viewForField release];
    [_tableView release];
    [_imageForHead release];
    [_picurl release];
    [_viewForText release];
    [_labelForTitle release];
    [_lableText release];
    [_labelForFollow release];
    [_buttonForBack release];
    [_arrModel release];
    [_viewForTitle release];
    [_textField release];
    [_strText release];
    
    [super dealloc];
}

#pragma mark 夜间模式
- (void)viewWillAppear:(BOOL)animated {
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"夜间模式"]) {
        
        [DKNightVersionManager nightFalling];
        
    } else {
        
        [DKNightVersionManager dawnComing];
    }
    
    self.tableView.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor], [UIColor blackColor]);
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.number = 0;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self handleData];
    [self createTableView];
    [self handleRefresh];
    [self data];
    [self createTitleOfTop];
    [self createNotification];
    
    [[NSNotificationCenter defaultCenter] addObserverForName:@"NoNet" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"网络提示" message:@"哎呀, 没有网络了 *_*" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:1 handler:^(UIAlertAction * _Nonnull action) {
            
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
            
        }];
        
        [alert addAction:action];
        
        [self presentViewController:alert animated:NO completion:^{
            
        }];
        
    }];
}

#pragma mark 创建tableView以及其它控件
- (void)createTableView {
    
    self.imageForHead = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]];
    
    [self.view addSubview:self.imageForHead];
    
    [_imageForHead release];
    
    self.imageForHead.frame = CGRectMake(0, 0, WIDTH, HEIGHT / 3);
    
    self.imageForHead.backgroundColor = [UIColor clearColor];
    
    self.viewForText = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 3)];
    
    [self.imageForHead addSubview:self.viewForText];
    
    [_viewForText release];
    
    //view上的text
    self.lableText = [[UILabel alloc] initWithFrame:CGRectMake(50, HEIGHT/8, WIDTH - 100, 80)];
    
    [self.viewForText addSubview:self.lableText];
    
    [_lableText release];
    
    self.lableText.textColor = [UIColor whiteColor];
    
    self.lableText.numberOfLines = 0;
    
    
    self.labelForFollow = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 2 - 60 , HEIGHT / 8 + 80, 120, 40)];
    
    self.labelForFollow.textColor = [UIColor whiteColor];
    
    [self.viewForText addSubview:self.labelForFollow];
    
    [_labelForFollow release];
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    
    self.tableView.tableHeaderView = self.imageForHead;
    
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;
    
    [_tableView release];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[QuestionTabViewCell class] forCellReuseIdentifier:@"pool"];
    
}

#pragma mark 处理数据
- (void)data {
    
    self.arrModel = [NSMutableArray array];
    
    NSString *url = [NSString stringWithFormat:@"http://c.3g.163.com/newstopic/qa/%@.html",self.model.expertId];
    
    [HandleData handleFloewNewWithString:url Block:^(id result) {
        
        NSDictionary *dic = [result objectForKey:@"data"];
        
        NSDictionary *dicExpert = [dic objectForKey:@"expert"];
        
        self.strText = [dicExpert objectForKey:@"description"];
        
        self.picurl = [dicExpert objectForKey:@"picurl"];
        
        [self.imageForHead sd_setImageWithURL:[NSURL URLWithString:self.picurl]];
        
        self.lableText.text = [dicExpert objectForKey:@"alias"];
        
        NSString *follow = [NSString stringWithFormat:@"- %@关注 -",[dicExpert objectForKey:@"concernCount"]];
        
        self.labelForFollow.text = follow;
        
    }];
    
    [self.tableView reloadData];
    
}

- (void)handleData {
    
    NSString *url1 = [NSString stringWithFormat:@"http://c.3g.163.com/newstopic/list/hotqa/%@/%ld-10.html",self.model.expertId,self.number];
    
    [HandleData handleFloewNewWithString:url1 Block:^(id result) {
        
        NSArray *arr = [result objectForKey:@"data"];
        
        for (NSDictionary *dicHotList in arr) {
            
            NSDictionary *dicQuestion = [dicHotList objectForKey:@"question"];
            
            ModelQuestion *model = [[ModelQuestion alloc] init];
            model.userName = [dicQuestion objectForKey:@"userName"];
            model.userHeadPicUrl = [dicQuestion objectForKey:@"userHeadPicUrl"];
            model.content  = [NSMutableArray array];
            [model.content addObject: [dicQuestion objectForKey:@"content"]];
            
            //answer
            NSDictionary *dicAnswer = [dicHotList objectForKey:@"answer"];
            
            model.specialistHeadPicUrl = [dicAnswer objectForKey:@"specialistHeadPicUrl"];
            model.specialistName = [dicAnswer objectForKey:@"specialistName"];
            [model.content addObject:[dicAnswer objectForKey:@"content"]];
            model.cTime = [dicAnswer objectForKey:@"cTime"];
            
            [self.arrModel addObject:model];
            
        }
        
    }];
    
    self.number = self.number + 10;
    
    [self.tableView reloadData];
    
}

#pragma 标题栏
- (void)createTitleOfTop {
    
    self.labelForTitle = [[UILabel alloc] initWithFrame:CGRectMake( 70, 10, WIDTH - 100, 50)];
    
    [self.viewForTitle addSubview:self.labelForTitle];
    
    self.labelForTitle.textColor = [ UIColor whiteColor];
    
    [_labelForTitle release];
    
    //返回button
    
    self.buttonForBack = [UIButton buttonWithType:UIButtonTypeCustom];
    
    self.buttonForBack.frame = CGRectMake(10, 20, 50, 50);
    
    [self.view addSubview:self.buttonForBack];
    
    [self.buttonForBack setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    
    [self.buttonForBack addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)back:(UIButton *)button {
    
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)createNotification {
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    CGFloat y = [[change objectForKey:@"new"] CGPointValue].y;
    
    if (y <= (HEIGHT/3)) {
        
        self.viewForTitle.backgroundColor = [UIColor colorWithRed:1 green:0 blue:0 alpha:(y / (HEIGHT/3))];
        
    } else {
        
        self.viewForTitle.backgroundColor = [UIColor redColor];
    }
    
    if (y > (HEIGHT/3)) {
        
        self.labelForTitle.text = self.strText ;
        
    }else {
        
        self.labelForTitle.text = @"";
        
    }
    
}

#pragma 键盘出现
- (void)keyboardWillShow:(NSNotification *)aNotification {
    
    NSDictionary *userInfo = [aNotification userInfo];
    
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    
    CGRect keyboardRect = [aValue CGRectValue];
    
    int height = keyboardRect.size.height;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self.viewForField.frame = CGRectMake(0, HEIGHT - height - 50, WIDTH, 50);
    }];
    
}

#pragma mark 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.arrModel.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    QuestionTabViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pool"];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    ModelQuestion *model = [self.arrModel objectAtIndex:indexPath.row];
    
    [cell passModelWith:model];
    
    cell.dk_backgroundColorPicker = DKColorWithColors([UIColor whiteColor],[UIColor colorWithWhite:0.247 alpha:1.000]);
    
    
    cell.labelForAnswerName.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor colorWithWhite:0.689 alpha:1.000]);
    
    cell.labelForAnswerContect.dk_textColorPicker = DKColorWithColors([UIColor blackColor], [UIColor colorWithWhite:0.689 alpha:1.000]);
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ModelQuestion * model = [self.arrModel objectAtIndex:indexPath.row];
    
    CGFloat h = [QuestionTabViewCell heightForCell:model];
    
    return h + 20;
}

#pragma mark 创建刷新
- (void)handleRefresh {
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        [self handleData];
        
        [self.tableView reloadData];
        
        [self.tableView.mj_footer endRefreshing];
    }];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        self.number = 0;
        [self handleData];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
    }];
    
}















- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
